﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AzureDiagMon.Common.Helpers
{   
    public static class  HumanReadableExtensions
    {
        public static string ToHumanReadable(this TimeSpan value)
        {
            var suffixes = new[] { "y", "w", "d", "h", "m", "s" };
            var multiplers = new double[] { 60 * 60 * 24 * 7 * 52,
                                            60 * 60 * 24 * 7,
                                            60 * 60 * 24,
                                            60 * 60,
                                            60,
                                            1};

            var seconds = value.TotalSeconds;
            if (seconds < 1)
            {
                if (value.TotalMilliseconds == 0d)
                {
                    return "0s";
                }
                return String.Format("{0} ms", value.TotalMilliseconds);
            }

            var parts = new List<string>();
            for (var i = 0; i < suffixes.Length; i++)
            {
                var x = (int)(seconds / multiplers[i]);
                if (x > 0)
                {
                    seconds = seconds % multiplers[i];
                    parts.Add(String.Format("{0}{1}", x, suffixes[i]));
                }
                if (seconds < 1)
                    break;
            }
            return String.Join(" ", parts);
        }

    }
}
